﻿using System;
using MessageSystem.Managed.Interface;

namespace MessageSystem.Managed.Rpc
{
    public class RpcProxy
    {
        private RpcDomain       _domain;
        private int             _sessionid;
        private RpcBroadCaster  _broadCaster;
        private RpcSessionService _session;

        public RpcProxy(RpcDomain domain,int sessionid,RpcBroadCaster caster,RpcSessionService session)
        {
            _domain = domain;
            _sessionid = sessionid;
            _broadCaster = caster;
            _session = session;
        }

        protected void Invoke(IMessage msg, bool encrypt, object callback)
        {
            UInt16 flags = 0;
            if (encrypt)
                flags = RpcControl.SetEncrypt(flags);
            int OpCode = 0;
            if (null != callback)
                OpCode = _session.PushCallback(callback);
            _domain.Invoke(msg, flags, _sessionid, OpCode);
        }

        public void Return(IMessage msg, bool encrypt,Int32 OpCode)
        {
            UInt16 flags = RpcControl.SetReturn(0);
            if (encrypt)
                flags = RpcControl.SetEncrypt(flags);
            _domain.Invoke(msg, flags, _sessionid,OpCode);
        }

        public RpcBroadCaster PrepareBroadcast()
        {
            _broadCaster.Prepare(this);
            return _broadCaster;
        }

        public void UnBind()
        {
            _session.UnBind();
        }

        public Int32 SessionId { get { return _sessionid; } }
    }
}
